// pages/result/result.js
const app = getApp()
const { ajax } = app.globalData
const audioDomA = wx.createInnerAudioContext() //原生
const audioDomB = wx.createInnerAudioContext() //作品伴奏
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollStyle: `height:calc(100% - ${wx.getStorageSync('navHeight')}px)`,
    contentId: '',
    sliderValue: 0,
    player: {
      status: 0,
      currentTime: 0,
      duration: 0,
    },
    openUpload: false,
    photoNav: ['我的形象', '本地相册'],
    currentPhotoSelect: 0,
    imageListMy: [], //我的形象
    chooseUrlIndex: null, //选中形象索引
    detail: {},

    denoiseList: [{
        imgUrl: 'https://www.hndt.com/miniIcon/AiOpera/result0.png',
        title: '音频降噪',
        value: '1'
      },
      {
        imgUrl: 'https://www.hndt.com/miniIcon/AiOpera/result1.png',
        title: '声音强化',
        value: '2'
      },
      {
        imgUrl: 'https://www.hndt.com/miniIcon/AiOpera/result2.png',
        title: '自动调音',
        value: '3'
      },
      {
        imgUrl: 'https://www.hndt.com/miniIcon/AiOpera/result3.png',
        title: '空间音效',
        value: '4'
      },
    ],
    denoiseValue: [],
    timbre: false,
    nickName: '',
    avatarUrl: ''
  },
  // 打开上传文件弹框
  handleUpload() {
    this.setData({
      openUpload: true
    })
  },
  // 选中形象图
  checkImg(e) {
    let index = e.currentTarget.dataset.index
    // 单选
    this.data.imageListMy.forEach((item, index) => {
      this.setData({
        [`imageListMy[${index}].checked`]: false
      })
    })
    this.setData({
      [`imageListMy[${index}].checked`]: true,
      chooseUrlIndex: index,
    })
    console.log(e)
  },
  // 暂停
  pauseAudio() {
    audioDomA.pause()
    audioDomB.pause()
    this.setData({
      'player.status': 2
    })
  },
  // 播放
  palyAudio() {
    audioDomA.play()
    audioDomB.play()
    this.setData({
      'player.status': 1
    })
  },

  // 详情
  getDetail() {
    this.data.denoiseList.forEach((ele, index) => {
      this.setData({
        [`denoiseList[${index}].checked`]: false
      })
    })
    console.log(this.data.detail.score)
    ajax.get('/singer/getCreationById', {
      contentId: this.data.contentId
    }).then(data => {
      if (data.code == 0) {
        this.setData({
          detail: data.data,
          'detail.score': Math.floor(Math.random() * (100 - 80 + 1)) + 80,
          'detail.accVolume': data.data.accVolume / 2,
          'detail.fileVolume': data.data.fileVolume / 2
        })
        audioDomA.src =  this.data.detail.accUrl //伴奏
        audioDomB.src =  this.data.detail.fileUrl //录音
        audioDomA.volume = this.data.detail.accVolume
        audioDomB.volume =  this.data.detail.fileVolume
        // 生成一个80-100的随机数
        this.setData({
        })
      }
    })



    this.setData({
      imageListMy: [{
          url: 'https://img2.baidu.com/it/u=3051605882,857880533&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=821'
        },
        {
          url: 'https://img1.baidu.com/it/u=3462988733,4004503434&fm=253&fmt=auto&app=138&f=JPEG?w=771&h=500'
        },
        {
          url: 'https://img0.baidu.com/it/u=35079958,3201967129&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=750'
        },
        {
          url: 'https://pic.rmb.bdstatic.com/bjh/f03519a1bdd63ffbf59060003448066c.jpeg'
        },
      ]
    })
    this.data.imageListMy.forEach((item, index) => {
      this.setData({
        [`imageListMy[${index}].checked`]: false
      })
    })
    audioDomA.onCanplay(() => {
      audioDomA.duration;
      let intervalTime = setInterval(()=> {
        if (audioDomA.duration !== 0) {
          this.setData({
            'player.duration': audioDomA.duration
          })
          clearInterval(intervalTime);
        }
      }, 500);
    })
    audioDomA.onTimeUpdate(() => {
      this.setData({
        'player.currentTime': audioDomA.currentTime
      })
      // 换算sliderValue的值
      let sliderValue = audioDomA.currentTime / audioDomA.duration * 100
      this.setData({
        sliderValue
      })
    })
    audioDomA.onEnded(() => {
      this.setData({
        'player.status': 3
      })
    })
  },
  // 进度条拖动
  sliderChange(e) {
    let value = e.detail.value
    let currentTime = value / 100 * audioDomA.duration
    audioDomA.seek(currentTime)
    audioDomA.play()
    audioDomB.seek(currentTime)
    audioDomB.play()
    this.setData({
      'player.currentTime': currentTime,
      'player.status': 1
    })
  },
  sliderChangeA(e) {
    let value = e.detail.value
    console.log(value)
    audioDomA.volume = value
  },
  sliderChangeB(e) {
    let value = e.detail.value
    console.log(value)
    audioDomB.volume = value
  },
  handleTimbre(){
    if(wx.getStorageSync('userInfo').level == 0){
      wx.showToast({
        mask: true,
        icon: 'error',
        title: `请先开通VIP`,
      })
      return
    }
    wx.showLoading({
      mask: true,
      title: `正在加载....`,
    })
    ajax.get('/train/getUserTrain', {
      userId: wx.getStorageSync('userInfo').userId,
    }).then(res => {
      wx.hideLoading()
      if (res.data) {
        this.setData({
          timbre: !this.data.timbre
        })
      }else{
        wx.showToast({
          mask: true,
          icon: 'error',
          title: `请先去创建模型`,
        })
      }
    })
  },
  selectNav(e) {
    let index = e.currentTarget.dataset.index
    // 调用本地图片
    if (index == 1) {
      wx.chooseImage({
        count: 1,
        success: (res) => {
          let filePath = res.tempFilePaths[0]
          console.log(filePath)
          ajax.upload('/upload', filePath).then(data => {
            let jsonData = JSON.parse(data)
            if (jsonData.code == 0) {
              this.setData({
                'detail.roleFile': jsonData.data,
                openUpload: false
              })
            }
          })
        },
      })
    }
  },
  chooseImg() {
    if (this.data.chooseUrlIndex != null) {
      this.setData({
        openUpload: false,
        'detail.roleFile': this.data.imageListMy[this.data.chooseUrlIndex].url
      })
    }
  },
  chooseImgNo() {
    this.setData({
      openUpload: false
    })
  },
   // 选中智能音效
  handleCheck(e) {
    let index = e.currentTarget.dataset.index
    this.setData({
      [`denoiseList[${index}].checked`]: !this.data.denoiseList[index].checked
    })
  },
  // 开始合成
  handleCreate() {
    if(!this.data.detail.roleFile){
      wx.showToast({
        icon: 'none',
        title: '请上传形象',
        duration: 2000
      })
      return
    }
    let denoiseValue = []
    this.data.denoiseList.forEach((item, index) => {
      if (item.checked) {
        denoiseValue.push(item.value)
      }
    })
    let params = {
      ...this.data.detail,
      contentId: this.data.contentId,
      accVolume: (audioDomB.volume * 2).toFixed(1), //伴奏音量
      fileVolume: (audioDomA.volume * 2).toFixed(1), //原音音量
      arr: denoiseValue,
    }
    console.log(params)
    wx.showLoading({
      mask: true,
      title: `正在加载....`,
    })
    ajax.post('/singer/updateTask', { ...params }).then(data => {
      console.log(data)
      if(data.code == 0){
        wx.switchTab({
          url: '/pages/me/me',
        })
      }
    })
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options, 'options')
    this.setData({
      contentId: options.contentId
      // contentId: '1784792248084480000'
    })
    this.getDetail()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      nickName: wx.getStorageSync('userInfo').nickName,
      avatarUrl: wx.getStorageSync('userInfo').avg
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    audioDomA.stop()
    audioDomB.stop()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.switchTab({
      url: '/pages/menu/menu',
    })
    audioDomA.stop()
    audioDomB.stop()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})